package com.Xingcang_Dianxue.WhutBank.Controllers.Client;

import com.Xingcang_Dianxue.WhutBank.Models.Model;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.ResourceBundle;


public class WithdrawalController implements Initializable {
    @FXML
    private Label ch_acc_num;

    @FXML
    private Label ch_acc_phonenumber;

    @FXML
    private Label ch_acc_username;

    @FXML
    private PasswordField ch_confirm_password;

    @FXML
    private PasswordField ch_password;

    @FXML
    private Label checking_acc_num;

    @FXML
    private Label checking_balance;

    @FXML
    private AnchorPane ch_container;
    @FXML
    private TextField ch_amount_withdrawal;

    @FXML
    private Button ch_btn;

    @FXML
    private Label time_lbl;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        ch_container.setVisible(true);
        bindData();
        withdrawal();
        updateTime();
    }

    private void updateTime() {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String timeText = formatter.format(date);
        Platform.runLater(() -> time_lbl.setText(timeText));
    }


    // 将用户信息绑定到界面上显示
    private void bindData() {
        // 判断用户是否有银行卡
        if (Model.getInstance().getClient().getCheckingAccount() != null) {
            // 卡片上的数据
            String[] checking_num = Model.getInstance().getClient().getCheckingAccount().getAccountNumber().split(" ");
            checking_acc_num.textProperty().bind(Bindings.concat(checking_num[0], " ", "****", " ", checking_num[2], " ", "****"));
            checking_balance.textProperty().bind(Bindings.concat("￥").concat(Model.getInstance().getClient().getCheckingAccount().balanceProperty()));
            // 银行卡号
            ch_acc_num.textProperty().bind(Bindings.concat(checking_num[0], " ", checking_num[1], " ", checking_num[2], " ", checking_num[3]));
            // 银行卡持卡人
            ch_acc_username.textProperty().bind(Model.getInstance().getClient().userNameProperty());
            // 持卡人手机号
            ch_acc_phonenumber.textProperty().bind(Model.getInstance().getClient().phoneNumberProperty());
        } else {
            ch_container.setVisible(false);
        }

    }

    private void withdrawal() {
        ch_btn.setOnAction(e -> {
            if (ch_amount_withdrawal.getText().isEmpty() || ch_password.getText().isEmpty() || ch_confirm_password.getText().isEmpty()) {
                showMessage("请填写完整信息");
                emptyFields();
            } else if (!ch_password.getText().equals(ch_confirm_password.getText())) {
                showMessage("密码不一致");
                emptyFields();
            } else {
                double amount = Double.parseDouble(ch_amount_withdrawal.getText());
                double newBalance = Model.getInstance().getClient().getCheckingAccount().getBalance() - amount;
                Model.getInstance().getDatabaseDriver().decreaseBalance("checking", ch_acc_phonenumber.getText(), amount);
                Model.getInstance().getClient().getCheckingAccount().balanceProperty().set(newBalance);
                Model.getInstance().totalExpensesProperty().set(Model.getInstance().totalExpensesProperty().get() + amount);

                String sender = Model.getInstance().getClient().phoneNumberProperty().get();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date createTime = new Date();
                Model.getInstance().getDatabaseDriver().saveTransaction(sender, sender, amount, simpleDateFormat.format(createTime), "银行卡取款", "取款");
                showMessage("取款成功");
                emptyFields();
            }
        });
    }


    private void emptyFields() {
        ch_amount_withdrawal.setText("");
        ch_password.setText("");
        ch_confirm_password.setText("");
    }

    private void showMessage(String message) {
        var alert = new Alert(Alert.AlertType.NONE);
        if (Objects.equals(message, "请填写完整信息")) {
            alert = new Alert(Alert.AlertType.WARNING);
        } else if (Objects.equals(message, "密码不一致")) {
            alert = new Alert(Alert.AlertType.ERROR);
        } else if (Objects.equals(message, "取款成功")) {
            alert = new Alert(Alert.AlertType.INFORMATION);
        }

        alert.setTitle("Information Dialog");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.initOwner(ch_acc_num.getScene().getWindow());
        alert.show();
    }

    private void show(Dialog<?> alert) {
        try {
            alert.getDialogPane().getStylesheets().addAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
